// 全局请求封装
// #ifdef APP
const base_url = 'http://192.168.8.67:8081/v1'
// #endif
// #ifdef H5
const base_url = '/api/v1'
// #endif
// const base_url = '/api/v1'
// 请求超出时间
const timeout = 10000

// 需要修改token，和根据实际修改请求头
export default ({
	URL,
	Method,
	Data,
	Header
}) => {
	let url = URL;
	let method = Method || "get";
	let data = Data || {};
	let header = {
		'Auth': uni.getStorageSync('token'),
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
		...Header
	}

	return new Promise((resolve, reject) => {
		uni.showLoading({
			mask: true,
			title: '请稍后...'
		})
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			timeout,
			success(response) {
				const res = response
				// 根据返回的状态码做出对应的操作
				uni.hideLoading()
				//获取成功
				if (res.statusCode === 200) {
					resolve(res.data);
				} else {
					uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: true,
								success: (res) => {
									if (res.confirm) {
										setTimeout(() => {
											uni.navigateTo({
												url: "/pages/login/login",
											})
										}, 1000);
									}

								},
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
								icon: 'none'
							})
							break;
						default:
							uni.showToast({
								title: '请重试...',
								duration: 2000,
								icon: 'none'
							})
							break;
					}
				}
			},
			fail(err) {
				uni.hideLoading()
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						mask: true,
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						icon: 'none',
						duration: 2000
					})
				}
				reject(err);
			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
			}
		});
	}).catch().finally(() => {
		uni.hideLoading()
	})

};